package upload

import (
	"errors"
	"fmt"
	"context"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"go.uber.org/zap"
	"mime/multipart"
	"path"
	"math/rand"
	"time"
	"wave-admin/global"
	"wave-admin/utils"
)

type Qiniu struct{}


//@object: *Qiniu
//@function: UploadFile
//@description: 上传文件
//@param: file *multipart.FileHeader
//@return: string, string, error
func (*Qiniu) UploadFile(file *multipart.FileHeader) ([]string, string, error) {
	putPolicy := storage.PutPolicy{Scope: global.GnConfig.Qiniu.Bucket}
	mac := qbox.NewMac(global.GnConfig.Qiniu.AccessKey, global.GnConfig.Qiniu.SecretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := qiniuConfig()
	formUploader := storage.NewFormUploader(cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{Params: map[string]string{"x:name": "github logo"}}

	f, openError := file.Open()
	if openError != nil {
		global.GnLog.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
		return nil, "", errors.New("function file.Open() Filed, err:" + openError.Error())
	}
	defer f.Close()                                                  // 创建文件 defer 关闭
	// 读取文件后缀
	ext := path.Ext(file.Filename)
	// 读取文件名并加密
	name := utils.Md5Encode(file.Filename + fmt.Sprintf("%d%04d",time.Now().Unix(), rand.Int31()))
	// 拼接新文件名
	filename := name + ext
	putErr := formUploader.Put(context.Background(), &ret, upToken, filename, f, file.Size, &putExtra)
	if putErr != nil {
		global.GnLog.Error("function formUploader.Put() Filed", zap.Any("err", putErr.Error()))
		return nil, "", errors.New("function formUploader.Put() Filed, err:" + putErr.Error())
	}
	urls := []string{utils.TransformImageUrl("/" + ret.Key)}

	return urls, ret.Key, nil
}

//@object: *Qiniu
//@function: qiniuConfig
//@description: 根据配置文件进行返回七牛云的配置
//@return: *storage.Config
func qiniuConfig() *storage.Config {
	cfg := storage.Config{
		UseHTTPS:      global.GnConfig.Qiniu.UseHttps,
		UseCdnDomains: global.GnConfig.Qiniu.UseCdnDomains,
	}
	switch global.GnConfig.Qiniu.Zone { // 根据配置文件进行初始化空间对应的机房
	case "ZoneHuadong":
		cfg.Zone = &storage.ZoneHuadong
	case "ZoneHuabei":
		cfg.Zone = &storage.ZoneHuabei
	case "ZoneHuanan":
		cfg.Zone = &storage.ZoneHuanan
	case "ZoneBeimei":
		cfg.Zone = &storage.ZoneBeimei
	case "ZoneXinjiapo":
		cfg.Zone = &storage.ZoneXinjiapo
	}
	return &cfg
}